import React, { Component } from 'react'
import {
    Modal,
    Flex,
    Icon
    } from 'antd-mobile';
import MyScroll from '../../components/MyScroll/MyScroll';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { parse } from 'query-string';

const alert = Modal.alert;
import { goto_search_title, goto_search_body } from "./GotoSearch.less"
import cartdelect from '../../assets/svg/cartdelect.svg';

class GotoSearch extends Component {
    constructor(props) {
        super(props);
        this.state = {
            value: parse(props.location.search).showKeyword ==undefined ? "" : parse(props.location.search).showKeyword ,
            arr:[],
            pageNo:1,
            hotWords:[],
            pagerCount:0
        };
       // console.log(props);

    }

    componentDidMount() {
        //this.refs.searchBar.onFocus();
        //  let memberId = window.localStorage.getItem('memberId');
        // if(memberId) {
        let history = window.localStorage.getItem('memberIdHistory');
        // console.log(history);
       // console.log(history!=null&&history.includes("[")&&history.includes("]")&&history.startsWith("[")&&history.endsWith("]"));

        if(history!=null&&history.includes("[")&&history.includes("]")){
            this.setState({
                arr:JSON.parse(history)
            })
        }else {
            this.setState({
                arr: []
            });
            let arr=[];
            //console.log(JSON.stringify(arr));
            window.localStorage.setItem('memberIdHistory',JSON.stringify(arr));
        }

       // this.getdata(this.state.pageNo)
    }

    // getdata=(pageNo)=>{
    //     Toast.loading();
    //     goodsApi.hotWords({ pageNo }).then(r=>{
    //         Toast.hide();
    //         if(r.result==1){
    //             this.setState({
    //                 hotWords:r.data,
    //                 pagerCount:r.pagerCount,
    //                 pageNo:pageNo
    //             })
    //         }else{
    //             Toast.fail(r.msg)
    //         }
    //     })
    // }

    // clickHandle=()=>{
    //     let newPageNo ;
    //     if(this.state.pageNo==this.state.pagerCount){
    //         newPageNo = 1;
    //     }else {
    //         newPageNo = this.state.pageNo+1;
    //     }
    //     this.getdata(newPageNo)
    // }

    onSubmit = (value) => {
        // let memberId = window.localStorage.getItem('memberId');
        // if(memberId){
        console.log(111);
       // let { value } = this.state;
        let history = window.localStorage.getItem('memberIdHistory');
        // console.log(history);
        if(!!history){
            let arr = JSON.parse(history);
            // console.log(arr);
            if(value!=''){
                arr.unshift(value);
                let array = Array.from(new Set(arr));
                if(array.length>10){
                    let newArr =  array.slice(0,10);
                    window.localStorage.setItem('memberIdHistory',JSON.stringify(newArr));
                }else {
                    window.localStorage.setItem('memberIdHistory',JSON.stringify(array));
                }
            }
        }else {
            let arr=[];
            arr.push(value);
            window.localStorage.setItem('memberIdHistory',JSON.stringify(arr));
        }
        // }
     //   console.log(value)
        //this.props.dispatch(routerRedux.replace(`/gotosearch?showKeyword=${encodeURIComponent(value)}`));
        this.props.dispatch(routerRedux.replace(`/goodsearch/keywordSearch?keyword=${encodeURIComponent(value)}&showKeyword=${encodeURIComponent(value)}`));
        // if (value == '') {
        //     this.props.dispatch(routerRedux.push(`/goodsearch/keywordSearch`));
        // } else {
        //     this.props.dispatch(routerRedux.push(`/goodsearch/keywordSearch?keyword=${encodeURIComponent(value)}&showKeyword=${encodeURIComponent(value)}`));
        // }

    }

    onChange = (e) => {
        this.setState({
            value: e.target.value
        });
    };

    render() {
        let { arr, value } = this.state;
        const { gotosearch } = this.props;
        const { list } = gotosearch;
       console.log( value);

        return (
        <Flex style={{
            height:"100%",
            background:"#fff"
        }} direction="column"
            //justify="between" alignContent="stretch"
        >

            <Flex className={ goto_search_title }>
                {/*<Icon type='left' style={{ paddingLeft:'0.1rem' }} onClick={() => this.props.router.goBack()}/>*/}
                <Flex className="search_input">
                    <form action="" onSubmit={ (e)=>{ this.onSubmit(value),e.preventDefault(); } }>
                        <input placeholder="请输入关键字搜索" autoFocus type="search" value={ value } onChange={this.onChange} />
                    </form>
                    <Icon className="search_icon" style={ value.length > 0 ? { color:"#fff" } : {} } type="search" size="md" />
                </Flex>
                {
                    value.length > 0 ?
                        <div className="search_cancelbtn" onClick={ ()=>{ this.onSubmit(value) } }>搜索
                        </div> :
                        <div className="search_cancelbtn" onClick={() => { this.props.dispatch(routerRedux.goBack()); }}>取消
                        </div>
                }
            </Flex>

            <MyScroll>
                {list.length!==0?<div className={ goto_search_body }>
                    <Flex justify="between" className="search_history">
                        <div>热门搜索</div>
                        {/*{*/}
                        {/*arr.length>0 ?  <Flex*/}
                        {/*// className="history_delect"*/}
                        {/*onClick={() => alert('提示', '确定删除全部记录？', [*/}
                        {/*{ text: '取消', onPress: () => {} },*/}
                        {/*{ text: '确定', onPress: () => {*/}
                        {/*window.localStorage.removeItem('memberIdHistory');*/}
                        {/*this.setState({*/}
                        {/*arr:[]*/}
                        {/*})*/}
                        {/*} },*/}
                        {/*])}*/}
                        {/*>*/}
                        {/*/!*<Icon type={cartdelect.id} />*!/*/}
                        {/*</Flex> :''*/}
                        {/*}*/}
                    </Flex>

                    {
                        list.length>0 ? <Flex wrap="wrap" style={{ paddingBottom:"0.3rem" }} justify="start">
                                {
                                    list.map((v,i,a)=>{
                                        return <div onClick={()=>{ this.onSubmit(v.keyWord) }} className="search_history_item" key={i}>
                                            {v.keyWord}
                                        </div>
                                    })
                                }
                            </Flex> :
                            <div style={{ textAlign:'center', margin:'1rem 0rem' }}>
                                无搜索历史
                            </div>

                    }
                </div>:""}



                <div style={{ width:"100%", height:"0.2rem", backgroundColor:"#F7F7F7" }} ></div>
                {arr.length!==0?<div className={ goto_search_body }>
                    {/*<WingBlank>历史搜索</WingBlank>*/}
                    {
                        arr.length>0 ?
                            <Flex justify="between" className="search_history">
                                <div>历史搜索</div>
                                     <Flex
                                       // className="history_delect"
                                        onClick={() => alert('提示', '确定删除全部记录？', [
                                            { text: '取消', onPress: () => {} },
                                            { text: '确定', onPress: () => {
                                                window.localStorage.removeItem('memberIdHistory');
                                                this.setState({
                                                    arr:[]
                                                })
                                            } },
                                        ])}
                                    >
                                        <Icon type={cartdelect.id} />
                                    </Flex>
                            </Flex>:''
                    }
                    {
                        arr.length > 0 ? <Flex wrap="wrap" justify="start">
                            {
                                arr.map((v,i,a)=>{
                                    return <div onClick={()=>{ this.onSubmit(v) }} className="search_history_item" key={i}>
                                        {v}
                                    </div>
                                })
                            }
                        </Flex> :''
                    /*
                     <div style={{ textAlign:'center', margin:'1rem 0rem' }}>
                     无搜索历史
                     </div>
                     */
                    }

                </div>:""}


            </MyScroll>

        </Flex>
        )
    }
}

export default connect(({ gotosearch }) => ({ gotosearch }))(GotoSearch);
